from flask import render_template, request, g, jsonify, redirect, current_app, abort

from info import db, constants
from info.models import Category, News, User
from info.response_code import RET
from info.utils.common import user_login_data
from info.utils.image_storage import storage
from . import profile_blu


@profile_blu.route('/other_news_list')
@user_login_data
def other_news_list():
    # 获取参数
    other_id = request.args.get('user_id')
    page = request.args.get('p', 1)
    news_list = []
    current_page = 1
    total_page = 1

    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    try:
        other = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    if not other:
        return jsonify(errno=RET.NODATA, errmsg='当前用户不存在')

    try:
        paginate = other.news_list.paginate(page, constants.OTHER_NEWS_PAGE_MAX_COUNT, False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        'news_list': news_dict_li,
        'current_page': current_page,
        'total_page': total_page
    }

    return jsonify(errno=RET.OK, errmsg='OK', data=data)


@profile_blu.route('/other_info')
@user_login_data
def other_info():
    user = g.user
    # 取到其他用户的id
    other_id = request.args.get('user_id')
    if not other_id:
        abort(404)

    others = None
    try:
        other_id = int(other_id)
        others = User.query.get(other_id)
    except Exception as e:
        current_app.logger.error(e)

    if not others:
        return jsonify(errno=RET.NODATA,errmsg='用户不存在')

    is_followed = False
    if user and others:
        if others in user.followed:
            is_followed = True

    data = {
        'is_followed': is_followed,
        'user':user.to_dict() if user else None,
        'other_info': others.to_dict()
    }

    return render_template('news/other.html', data=data)


@profile_blu.route('/user_follow')
@user_login_data
def user_follow():
    user = g.user
    page = request.args.get('p', 1)
    followed_list = []
    current_page = 1
    total_page = 1
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        paginate = user.followed.paginate(page,constants.USER_FOLLOWED_MAX_COUNT,False)
        followed_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    followed_dict_li = []
    for followed in followed_list:
        followed_dict_li.append(followed.to_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'users': followed_dict_li
    }

    return render_template('news/user_follow.html', data=data)


@profile_blu.route('/news_list', methods=['get', 'post'])
@user_login_data
def user_news_list():
    user = g.user
    page = request.args.get('p', 1)
    news_list = []
    current_page = 1
    total_page = 1
    try:
        page = int(page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1

    try:
        paginate = News.query.filter(News.user_id==user.id).paginate(page,constants.USER_COLLECTION_MAX_NEWS,False)
        news_list = paginate.items
        current_page = paginate.page
        total_page = paginate.pages
    except Exception as e:
        current_app.logger.error(e)

    news_dict_li = []
    for news in news_list:
        news_dict_li.append(news.to_review_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'news_list': news_dict_li
    }
    return render_template('news/user_news_list.html', data=data)


@profile_blu.route('/news_release', methods=['get', 'post'])
@user_login_data
def news_release():
    if request.method == 'GET':
        # 加载新闻分类数据
        categories = []
        try:
            categories = Category.query.all()
        except Exception as e:
            current_app.logger.error(e)

        categories_li = []
        for category in categories:
            categories_li.append(category.to_dict())

        # 移除最新分类
        categories_li.pop(0)

        data = {
            'categories': categories_li
        }
        return render_template('news/user_news_release.html', data=data)

    # 1.获取要提交的数据
    # 标题
    title = request.form.get('title')
    # 新闻来源
    source = '个人发布'
    # 摘要
    digest = request.form.get('digest')
    # 新闻内容
    content = request.form.get('content')
    # 索引图片
    index_image = request.files.get('index_image')
    # 分类id
    category_id = request.form.get('category_id')

    # 2校验参数
    # 2.1 判断数据是否有值
    if not all([title,digest,content,index_image,category_id]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    try:
        category_id = int(category_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    # 2.2取到图片，上传到七牛云
    try:
        index_image_data = index_image.read()
        key = storage(index_image_data)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR,errmsg='上传失败')
    # 3. 初始化新闻模型，并设置相关数据
    news = News()
    news.title = title
    news.digest = digest
    news.source = source
    news.content = content
    news.index_image_url = constants.QINIU_DOMIN_PREFIX + key
    news.category_id = category_id
    news.user_id = g.user.id
    # 3.1代表待审核状态
    news.status = 1

    # 提交到数据库
    try:
        db.session.add(news)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据保存失败')

    # 5. 返回结果
    return jsonify(errno=RET.OK, errmsg="发布成功，等待审核")


@profile_blu.route('/collection')
@user_login_data
def user_collection():
    user = g.user
    # 获取页数
    p = request.args.get('p', 1)
    try:
        p = int(p)
    except Exception as e:
        current_app.logger.error(e)
        p = 1

    collections = []
    current_page = 1
    total_page = 1
    try:
        # 进行分页查询
        paginate = user.collection_news.paginate(p, constants.USER_COLLECTION_MAX_NEWS, False)
        collections = paginate.items
        current_page = paginate.page
        total_page = paginate.pages

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='数据查询错误')

    collections_news_li = []

    for news in collections:
        collections_news_li.append(news.to_dict())

    data = {
        'current_page': current_page,
        'total_page': total_page,
        'collections': collections_news_li
    }

    return render_template('news/user_collection.html', data=data)


@profile_blu.route('/pass_info', methods=['get', 'post'])
@user_login_data
def pass_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pass_info.html')
    # 获取参数
    old_password = request.json.get('old_password')
    new_password = request.json.get('new_password')

    # 校验参数
    if not all(['old_password', 'new_password']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数不足')

    # 校验原密码是否正确
    if not user.check_password(old_password):
        return jsonify(errno=RET.PWDERR, errmsg='原密码错误')

    user.password = new_password

    return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/pic_info', methods=['get', 'post'])
@user_login_data
def pic_info():
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_pic_info.html', data={'user': user.to_dict()})
    # 获取参数
    try:
        avatar = request.files.get('avatar').read()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg='文件读取错误')
    # 将文件上传到七牛云
    try:
        url = storage(avatar)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.THIRDERR, errmsg='图片上传错误')

    # 将用户头像保存
    user.avatar_url = url

    return jsonify(errno=RET.OK, errmsg='上传成功', data={'avatar_url': constants.QINIU_DOMIN_PREFIX + url})


@profile_blu.route('/base_info', methods=['get', 'post'])
@user_login_data
def base_info():
    """
        用户基本信息
        1. 获取用户登录信息
        2. 获取到传入参数
        3. 更新并保存数据
        4. 返回结果
        :return:
        """
    user = g.user
    if request.method == 'GET':
        return render_template('news/user_base_info.html', data={'user': user.to_dict()})
    # 获取参数
    nick_name = request.json.get('nick_name')
    signature = request.json.get('signature')
    gender = request.json.get('gender')
    # 校验参数
    if not all([nick_name, signature, gender]):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')

    if gender not in (['MAN', 'WOMAN']):
        return jsonify(errno=RET.PARAMERR, errmsg='参数错误')
    # 更新并保存数据
    user.nick_name = nick_name
    user.signature = signature
    user.gender = gender

    return jsonify(errno=RET.OK, errmsg='修改成功')


@profile_blu.route('/info')
@user_login_data
def user_info():
    user = g.user
    if not user:
        return redirect('/')
    data = {
        'user': user.to_dict()
    }
    return render_template('news/user.html', data=data)
